<template>
  <div class="publish-container">
    <!-- 头部导航 -->
    <div class="header">
      <h1 class="page-title">发布新话题</h1>
      <div class="header-actions">
        <button @click="toforum" class="back-button">
          <i class="el-icon-arrow-left"></i> 返回论坛
        </button>
      </div>
    </div>

    <!-- 发布表单 -->
    <div class="form-container">
      <el-form ref="form" :model="form" label-width="80px" class="publish-form">
        <!-- 标题 -->
        <el-form-item label="标题">
          <el-input
              v-model="TipTitel"
              placeholder="请输入标题（15字以内）"
              maxlength="15"
              show-word-limit
              class="title-input"></el-input>
        </el-form-item>

        <!-- 帖子类型选择 -->
        <el-form-item label="分类">
          <div class="tiptype-container">
            <div class="tiptype-list">
              <div 
                v-for="(type, index) in currentPageTypes" 
                :key="index"
                :class="['tiptype-item', { 'active': TipTypeId === type.tipTypeId }]"
                @click="selectTipType(type.tipTypeId)">
                {{ type.tipTypeName }}
              </div>
            </div>
            <div class="tiptype-pagination">
              <el-button size="small" @click="changePage(-1)" :disabled="currentPage <= 1">
                <i class="el-icon-arrow-left"></i>
              </el-button>
              <span class="page-info">{{ currentPage }}/{{ totalPages }}</span>
              <el-button size="small" @click="changePage(1)" :disabled="currentPage >= totalPages">
                <i class="el-icon-arrow-right"></i>
              </el-button>
              <el-button size="small" type="text" @click="refreshTipTypes">换一批</el-button>
            </div>
          </div>
        </el-form-item>

        <!-- 封面上传 -->
        <el-form-item label="封面">
          <div class="upload-wrapper">
            <el-upload
                :disabled="form.coverPath !== '' && form.coverPath !== null"
                :file-list="fileList"
                :multiple="false"
                drag
                ref="uploadCover"
                action="#"
                list-type="picture"
                :auto-upload="false"
                class="upload"
                accept="image/*"
                :on-change="handleChange"
                :on-remove="handleRemove">
              <div v-if="form.coverPath === '' || form.coverPath === null" class="upload-placeholder">
                <i class="el-icon-picture-outline-round"></i>
                <div class="upload-text">
                  点击或拖拽上传封面图片
                </div>
                <div class="upload-hint">
                  支持 JPG、PNG 格式，不超过 2MB
                </div>
              </div>
              <div v-else class="preview-container">
                <el-image
                    :preview-src-list="[form.coverPath.url || form.coverPath]"
                    :src="form.coverPath.url || form.coverPath"
                    class="preview-image"
                    fit="cover"
                    ref="urlImg"></el-image>
                <div class="preview-actions">
                  <i class="el-icon-delete" @click.stop="handleRemove"></i>
                  <i class="el-icon-zoom-in" @click="handlePreview"></i>
                </div>
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 内容（富文本编辑器） -->
        <el-form-item label="内容">
          <div class="editor-container">
            <div style="border: 1px solid #ccc;">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editor"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 400px; overflow-y: hidden;"
                  v-model="editorHtml"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
                  @onChange="handleChange"
                  @onDestroyed="handleDestroyed"
                  @onFocus="handleFocus"
                  @onBlur="handleBlur"
                  @customAlert="customAlert"
              />
            </div>
            <div class="editor-word-count">{{ editorWordCount }}/5000</div>
          </div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item class="form-actions">
          <el-button type="primary" @click.prevent="publish" class="submit-button">
            <i class="el-icon-s-promotion"></i> 发布话题
          </el-button>
          <el-button @click="toforum" class="cancel-button">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 遮罩层 -->
    <div v-if="loading" class="loading-overlay">
      <loading/>
    </div>
  </div>
</template>

<script>
import {addtip, postPic, deletePic, createRank} from "@/api/api";
import Loading from "@/components/Loading.vue";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

export default {
  name: 'TopicForm',
  components: {
    Loading,
    Editor,
    Toolbar
  },
  data() {
    return {
      loading: false,
      fileList: [],
      TipTitel: '',
      deptlist: [], // 保留兼容性
      tipTypeList: [], // 帖子类型列表
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      totalPages: 1, // 总页数
      TipTypeId: 0, // 选中的帖子类型ID
      TipPictrue: null,
      TipText: '',
      form: {
        coverPath: ''
      },
      // 编辑器实例，必须用 shallowRef
      editor: null,
      // 编辑器内容 HTML
      editorHtml: '',
      // 编辑器配置
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            // 自定义上传
            customUpload: this.uploadImage
          }
        }
      },
      // 工具栏配置
      toolbarConfig: {
        // 插入图片菜单的配置
        excludeKeys: []
      },
      // 组件模式
      mode: 'default',
      // 编辑器文字计数
      editorWordCount: 0
    };
  },
  created() {
    this.initTipTypes();
  },
  beforeDestroy() {
    // 组件销毁时，销毁编辑器
    this.destroyEditor();
  },
  computed: {
    // 当前页的帖子类型列表
    currentPageTypes() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tipTypeList.slice(start, end);
    }
  },
  methods: {
    // 添加图片
    async uploadImage(file, insertFn) {
      try {
        this.loading = true;
        const response = await postPic(file);
        // 插入图片到编辑器
        insertFn(response.data, '', '');
        this.loading = false;
      } catch (error) {
        this.$message.error('图片上传失败');
        this.loading = false;
        console.error('图片上传失败：', error);
      }
    },

    // 编辑器创建完成时的回调
    handleCreated(editor) {
      this.editor = Object.seal(editor); // 记录 editor 实例
      this.updateWordCount();
    },
    // 更新字数统计
    updateWordCount() {
      const text = this.editor?.getText() || '';
      this.editorWordCount = text.length;

      // 如果字数超限，显示提示
      if (this.editorWordCount > 5000) {
        this.$message.warning('内容超出字数限制');
      }
    },

    // 编辑器销毁时的回调
    handleDestroyed() {
      this.editor = null;
    },

    // 编辑器获取焦点时的回调
    handleFocus() {
      console.log('editor focus');
    },

    // 编辑器失去焦点时的回调
    handleBlur() {
      console.log('editor blur');
    },

    // 自定义提示
    customAlert(info, type) {
      this.$message({
        message: info,
        type: type === 'success' ? 'success' : type === 'warning' ? 'warning' : 'error'
      });
    },

    // 销毁编辑器
    destroyEditor() {
      const editor = this.editor;
      if (editor == null) return;
      editor.destroy();
    },

    // 初始化帖子类型数据
    initTipTypes() {
      // 从store中获取帖子类型列表
      this.tipTypeList = this.$store.state.tipTypeList;
      
      // 如果store中没有帖子类型数据，则触发获取
      if (this.tipTypeList.length === 0) {
        this.loading = true;
        this.$store.dispatch('fetchTipTypes').then(() => {
          this.tipTypeList = this.$store.state.tipTypeList;
          this.totalPages = Math.ceil(this.tipTypeList.length / this.pageSize);
          
          // 如果有帖子类型，默认选中第一个
          if (this.tipTypeList.length > 0) {
            this.TipTypeId = this.tipTypeList[0].tipTypeId;
          }
          this.loading = false;
        }).catch(error => {
          console.error('获取帖子类型失败:', error);
          this.$message.error('获取帖子类型失败');
          this.loading = false;
        });
      } else {
        // 直接使用store中的数据
        this.totalPages = Math.ceil(this.tipTypeList.length / this.pageSize);
        
        // 如果有帖子类型，默认选中第一个
        if (this.tipTypeList.length > 0) {
          this.TipTypeId = this.tipTypeList[0].tipTypeId;
        }
      }
    },
    
    // 选择帖子类型
    selectTipType(tipTypeId) {
      this.TipTypeId = tipTypeId;
    },
    
    // 切换页码
    changePage(direction) {
      const newPage = this.currentPage + direction;
      if (newPage >= 1 && newPage <= this.totalPages) {
        this.currentPage = newPage;
      }
    },
    
    // 刷新帖子类型（换一批）
    refreshTipTypes() {
      // 如果有下一页，切换到下一页
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      } else {
        // 否则回到第一页
        this.currentPage = 1;
      }
      
      // 如果store中的帖子类型为空，则重新获取
      if (this.$store.state.tipTypeList.length === 0) {
        this.loading = true;
        this.$store.dispatch('fetchTipTypes').then(() => {
          this.tipTypeList = this.$store.state.tipTypeList;
          this.totalPages = Math.ceil(this.tipTypeList.length / this.pageSize);
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }
    },

    handleChange(file) {
      // 检查是否有文件被选择
      if (!file) {
        return;
      }

      // 检查文件类型
      let isAccept = new RegExp('image/*').test(file.raw.type);
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件');
        return;
      }

      // 检查文件大小
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB');
        return;
      }

      // 清除之前的文件
      this.$refs.uploadCover.clearFiles();

      // 设置新文件
      this.form.coverPath = file;
      this.fileList[0] = file;
    },

    handleRemove() {
      const el = this.$refs.urlImg.$el;
      el.classList.add('flipOutX');
      setTimeout(() => {
        el.classList.remove('flipOutX');
        this.fileList = [];
        this.$refs.uploadCover.clearFiles();
        this.form.coverPath = '';
      }, 500);
    },

    handlePreview() {
      this.$refs.urlImg.showViewer = true;
    },

    async publish() {
      // 表单验证
      if (!this.TipTitel.trim()) {
        this.$message.warning('请输入话题标题');
        return;
      }

      // 获取富文本编辑器内容
      const html = this.editorHtml;
      if (!html || html === '<p><br></p>') {
        this.$message.warning('请输入话题内容');
        return;
      }

      if (this.editorWordCount > 5000) {
        this.$message.warning('内容超出字数限制（5000字）');
        return;
      }

      this.loading = true;
      try {
        console.log('开始发布帖子...');
        const response = await addtip({
          TipTitel: this.TipTitel,
          TipText: html,
          TipPictrue: this.form.coverPath?.raw,
          TipTypeId: this.TipTypeId,
        });

        console.log('发布帖子响应:', response);

        if (response.data.message === "成功") {
          // 检查今天是否已经发布过帖子
          const today = new Date().toISOString().split('T')[0];
          const publishCount = parseInt(localStorage.getItem(this.$store.state.myName+`publishCount_${today}`) || '0');

          console.log('今日发布次数:', publishCount);
          console.log('当前用户邮箱:', this.$store.state.me.userEmail);

          // 如果今天发布次数小于3次，增加积分
          if (publishCount < 3) {
            try {
              console.log('尝试增加积分...');
              const rankResponse = await createRank(
                this.$store.state.me.userEmail,
                4
              );

              console.log('积分增加响应:', rankResponse);

              // 更新今天的发布次数
              localStorage.setItem(this.$store.state.myName+`publishCount_${today}`, publishCount + 1);

              // 如果是第一次发布，显示积分增加提示
              if (publishCount === 0) {
                this.$message({
                  message: '发布成功！获得4积分奖励',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: '发布成功！',
                  type: 'success'
                });
              }
            } catch (error) {
              console.error('增加积分失败:', error);
              this.$message({
                message: '发布成功，但增加积分失败',
                type: 'warning'
              });
            }
          } else {
            this.$message({
              message: '发布成功！今日发布次数已达上限，不再获得积分',
              type: 'success'
            });
          }

          this.$router.push('/Main/forum');
        } else {
          this.$message.error("发布失败");
        }
      } catch (error) {
        console.error('发布失败:', error);
        this.$message.error("发布失败");
      } finally {
        this.loading = false;
      }
    },

    toforum() {
      this.$router.push('/Main/forum');
    },
  },
};
</script>

<style lang="scss" scoped>
.publish-container {
    min-height: 100vh;
    background-color: #f7f9fc;
    padding-bottom: 60px;
}

.header {
    background-color: #fff;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 32px;
}

.page-title {
    font-size: 22px;
    font-weight: 600;
    color: #333;
    margin: 0;
}

.back-button {
    display: flex;
    align-items: center;
    gap: 6px;
    background-color: transparent;
    color: #456ddc;
    border: 1px solid #e0e5ef;
    border-radius: 6px;
    padding: 8px 16px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
        background-color: #f0f2f7;
        color: #3a5dc0;
    }

    i {
        font-size: 16px;
    }
}

.form-container {
    max-width: 800px;
    margin: 0 auto;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    padding: 32px;
}

.publish-form {
    .el-form-item {
        margin-bottom: 24px;
    }

    .el-form-item__label {
        color: #333;
        font-weight: 500;
    }
}

.title-input {
    &::v-deep .el-input__inner {
        border-radius: 8px;
        border: 1px solid #e0e5ef;
        padding: 12px 16px;
        height: auto;
        transition: all 0.3s;

        &:focus {
            border-color: #456ddc;
            box-shadow: 0 0 0 2px rgba(69, 109, 220, 0.1);
        }
    }

    &::v-deep .el-input__count {
        background: transparent;
        font-size: 12px;
        color: #999;
    }
}

.tiptype-container {
    width: 100%;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 15px;
    background-color: #fff;
}

.tiptype-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 15px;
}

.tiptype-item {
    padding: 8px 15px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    background-color: #f5f7fa;
    font-size: 14px;
    
    &:hover {
        border-color: #409eff;
        color: #409eff;
    }
    
    &.active {
        background-color: #ecf5ff;
        border-color: #409eff;
        color: #409eff;
    }
}

.tiptype-pagination {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    
    .page-info {
        margin: 0 10px;
        color: #606266;
        font-size: 14px;
    }
}

.upload-wrapper {
    width: 100%;

    .upload {
        width: 100%;

        &::v-deep .el-upload-dragger {
            width: 100%;
            height: 200px;
            border: 2px dashed #e0e5ef;
            border-radius: 8px;
            background-color: #f9fafc;
            transition: all 0.3s;

            &:hover {
                border-color: #456ddc;
            }
        }
    }
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #999;

    i {
        font-size: 48px;
        margin-bottom: 16px;
        color: #ccc;
    }

    .upload-text {
        font-size: 16px;
        margin-bottom: 8px;
    }

    .upload-hint {
        font-size: 12px;
        color: #aaa;
    }
}

.preview-container {
    position: relative;
    width: 100%;
    height: 300px;
    overflow: hidden;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f9fafc;

    &:hover .preview-actions {
        opacity: 1;
    }
}

.preview-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    margin: 0 auto;
}

.preview-actions {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 24px;
    opacity: 0;
    transition: opacity 0.3s;

    i {
        font-size: 24px;
        color: white;
        cursor: pointer;
        padding: 8px;
        border-radius: 50%;
        transition: all 0.3s;

        &:hover {
            background-color: rgba(255, 255, 255, 0.2);
            transform: scale(1.1);
        }
    }
}

.editor-container {
    width: 100%;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 12px;
}

.editor-word-count {
    text-align: right;
    font-size: 12px;
    color: #999;
    margin-top: 8px;
}

.form-actions {
    margin-top: 32px;
    display: flex;
    justify-content: flex-start;

    &::v-deep .el-form-item__content {
        display: flex;
        gap: 16px;
    }
}

.submit-button {
    background-color: #456ddc;
    border-color: #456ddc;
    border-radius: 8px;
    padding: 12px 24px;
    font-size: 16px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.3s;

    &:hover {
        background-color: #3a5dc0;
        border-color: #3a5dc0;
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(69, 109, 220, 0.3);
    }

    &:active {
        transform: translateY(0);
    }

    i {
        font-size: 16px;
    }
}

.cancel-button {
    border-radius: 8px;
    padding: 12px 24px;
    font-size: 16px;
    transition: all 0.3s;

    &:hover {
        background-color: #f0f2f7;
    }
}

.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.7);
    backdrop-filter: blur(4px);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

// 动画效果
.flipOutX {
    animation: flipOutX 0.5s ease-in-out;
}

@keyframes flipOutX {
    from {
        transform: perspective(400px);
    }

    30% {
        transform: perspective(400px) rotateX(-20deg);
        opacity: 1;
    }

    to {
        transform: perspective(400px) rotateX(90deg);
        opacity: 0;
    }
}
</style>

<style src="@wangeditor/editor/dist/css/style.css"></style>
